<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="500" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm" label-width="100px" label-position="left">
			<el-form-item label="上级" prop="pid">
				<el-cascader v-model="form.pid" :options="groups" :props="groupsProps" :show-all-levels="false" clearable style="width: 100%;"></el-cascader>
			</el-form-item>
			<el-form-item label="名称" prop="name">
				<el-input v-model="form.name" clearable></el-input>
			</el-form-item>
			<el-form-item label="排序" prop="sort">
				<el-input v-model="form.sort" clearable></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible=false" >取 消</el-button>
			<el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script>
	export default {
		emits: ['success', 'closed'],
		data() {
			return {
				mode: "create",
				titleMap: {
					create: '新增',
					update: '编辑',
				},
				visible: false,
				isSaveing: false,
				form: {
					id:"",
					name: "",
					pid: 0,
					sort: 0,
				},
				rules: {},
				groups: [],
				groupsProps: {
					value: "id",
					emitPath: false,
					label: 'name',
					checkStrictly: true
				}

			}
		},
		mounted() {
			this.getGroup()
		},
		methods: {
			open(mode='create'){
				this.mode = mode;
				this.visible = true;
				return this
			},
			async getGroup(){
				var res = await this.$API.system.config.group.read.get();
				this.groups = res.data;
			},
			submit(){
				if(!this.form.pid){
					this.form.pid = 0;
				}
				this.$refs.dialogForm.validate(async (valid) => {
					if (valid) {
						this.isSaveing = true;
						var res = await this.$API.system.config.group[this.mode].post(this.form);
						this.isSaveing = false;
						if(res.code == 200){
							this.$emit('success', this.form, this.mode)
							this.visible = false;
							this.$message.success(res.message)
						}else{
							this.$alert(res.message, "提示", {type: 'error'})
						}
					}
				})
			},
			setData(data){
				Object.assign(this.form, data)
			}
		}
	}
</script>

<style>
</style>
